import { LineBreak, MysqlCommandProps } from "@/constant";
import { IColumn, IConfiguration } from "@/types";

function generateTable (tableName, columns: IColumn[], needDefaultProps: boolean, configuration: IConfiguration) {
    const { engine, charset, collate } = configuration;
    const primaryKeys: string[] = [];
    const uniqueKeys: string[] = [];
    let command = `CREATE TABLE \`${tableName}\` (` + LineBreak;
    if (needDefaultProps || needDefaultProps === undefined) {
        // 需要默认的 id、create_at 属性
        command += `  \`id\` int NOT NULL AUTO_INCREMENT,${LineBreak}`;
        command += `  \`create_at\` date NOT NULL,${LineBreak}`;
        primaryKeys.push('id');
    }
    columns.forEach((col) => {
        const { name, type, primaryKey, unique, default: def, ...props } = col;
        const otherProps = Object.keys(props).filter((key) => {
            if (typeof props[key] === 'boolean') return props[key];
            else return true;
        }).map((key) => MysqlCommandProps[key]).join(' '); // such as: NOT NULL AUTO_INCREMENT
        command += `  \`${name}\` ${type.toLowerCase()} ${otherProps} ${def ? `${MysqlCommandProps.default} '${def}'` : ''},${LineBreak}`;
        if (primaryKey) primaryKeys.push(name);
        if (unique) uniqueKeys.push(name);
    });
    if (primaryKeys.length) {
        command += `  ${MysqlCommandProps.primaryKey} (`;
        primaryKeys.forEach((keyName) => {
            command += `\`${keyName}\`,`
        })
        command = command.substring(0, command.length - 1);
        command += (uniqueKeys.length > 0 ? ")," : ")") + LineBreak;
    }
    uniqueKeys.forEach((keyName, index) => {
        command += `  ${MysqlCommandProps.unique} (\`${keyName}\`)${ index === (uniqueKeys.length - 1) ? '' : ','}${LineBreak}`;
    })
    command += `) ENGINE=${engine} DEFAULT CHARSET=${charset} COLLATE=${collate};${LineBreak}`;
    return command;
};

export {
    generateTable,
}